package com.example.user.myfirstapp.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.user.myfirstapp.MainActivity;
import com.example.user.myfirstapp.MyApplication;
import com.example.user.myfirstapp.R;
import com.example.user.myfirstapp.common.Constant;
import com.example.user.myfirstapp.common.LoadingDialog;
import com.example.user.myfirstapp.common.StringHelper;
import com.example.user.myfirstapp.entity.UserInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by user on 2016/9/22.
 */
public class EditPwdActivity extends Activity implements View.OnClickListener{
    private Button bt_editPwd_return,bt_save;
    private EditText et_oldPwd,et_newPwd,et_newPwd1;
    private Intent intent;
    private String oldPwd,newPwd,newPwd1,md5_pwd,md5_oldPwd;
    private int userId=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_pwd);

        //返回按钮
        bt_editPwd_return=(Button)findViewById(R.id.bt_editPwd_return);
        bt_editPwd_return.setOnClickListener(this);

        et_oldPwd=(EditText)findViewById(R.id.et_oldPwd);
        et_newPwd=(EditText)findViewById(R.id.et_newPwd);
        et_newPwd1=(EditText)findViewById(R.id.et_newPwd1);

        //保存
        bt_save=(Button)findViewById(R.id.bt_save);
        bt_save.setOnClickListener(this);
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_editPwd_return:
                finish();
                //从左往右切换
                this.overridePendingTransition(0,R.animator.slide_right_out);
                break;
            case R.id.bt_save:
                save();
                break;
            default:
                break;
        }
    }

    //保存
    private void save(){
        try {
            oldPwd = et_oldPwd.getText().toString();
            newPwd = et_newPwd.getText().toString();
            newPwd1 = et_newPwd1.getText().toString();

            if (TextUtils.isEmpty(oldPwd)) {
                Toast.makeText(this, "请输入旧密码", Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(newPwd)) {
                Toast.makeText(this, "请输入新密码", Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(newPwd1)) {
                Toast.makeText(this, "请再次输入新密码", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!newPwd.equals(newPwd1)) {
                Toast.makeText(this, "两次输入的新密码不同", Toast.LENGTH_SHORT).show();
                return;
            }

            //获取SharedPreferences参数
            SharedPreferences sp = getSharedPreferences(Constant.sharedPreferences_user_key, Context.MODE_PRIVATE);
            String userJson = sp.getString("userJson", "");
            if (!TextUtils.isEmpty(userJson)) {
                Gson gson = new Gson();
                UserInfo user = gson.fromJson(userJson, new TypeToken<UserInfo>() {}.getType());
                if(!user.equals("null")){
                    userId=user.getId();
                    md5_oldPwd=user.getUserPwd();
                }

            }
            String md5OldPwd=StringHelper.md5EncryptString(oldPwd);
            if(!md5_oldPwd.equals(md5OldPwd)){
                Toast.makeText(this, "您输入的原密码不正确", Toast.LENGTH_SHORT).show();
                return;
            }

            //显示加载中
            LoadingDialog.showLoading(this, "请稍后...");
            md5_pwd = StringHelper.md5EncryptString(newPwd);
            String url = "http://" + Constant.host + ":" + Constant.port + "/api/UserInfo/EditPwd";
            StringRequest request = new StringRequest(Request.Method.POST, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String result) {
                            if (result.equals("true")) {
                                //传值到登陆页
                                gotoLogin();
                                //关闭提示语
                                LoadingDialog.closeLoading();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError err) {
                            Toast.makeText(getApplicationContext(), "网络请求失败",
                                    Toast.LENGTH_LONG).show();
                            //关闭提示语
                            LoadingDialog.closeLoading();
                        }
                    }
            ) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> params = new HashMap<>();
                    params.put("oldPwd", md5_pwd);
                    params.put("newPwd", md5_pwd);
                    params.put("userId", Integer.toString(userId));
                    return params;
                }
            };
            request.setTag("editPwdRequest");
            MyApplication.getHttpQueue().add(request);
        }
        catch (Exception e)
        {
            Toast.makeText(this, "修改密码失败", Toast.LENGTH_SHORT).show();
            //关闭提示语
            LoadingDialog.closeLoading();
        }
    }

    private void gotoLogin(){
        //清空SharedPreferences
        SharedPreferences sp = getSharedPreferences(Constant.sharedPreferences_user_key, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.commit();

        //跳转
        intent = new Intent(EditPwdActivity.this,MainActivity.class);
        Bundle bundle=new Bundle();
        bundle.putInt("openFragmentCode",4);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        //结束时队列里面注销
        MyApplication.getHttpQueue().cancelAll("editPwdRequest");
    }
}
